package day2.assignments;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class Login
 */
@WebServlet(name = "Login", urlPatterns = { "/Login" }, displayName = "Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ServletConfig cfg;
	ServletContext ctx;
	Context dbCtx;
	RequestDispatcher rd;
	Connection con;
	DataSource ds;
	ResultSet rs;
	Statement stmt;

	public void init(ServletConfig cfg) {
		this.cfg = cfg;
		ctx = cfg.getServletContext();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String user = request.getParameter("user");
			String pswd = request.getParameter("pswd");

			ctx.setAttribute("username", user);
			ctx.setAttribute("password", pswd);

			dbCtx = new InitialContext();
			ds = (DataSource) dbCtx.lookup("jdbc/mydata");
			con = ds.getConnection();
			stmt = con.createStatement();
			rs = stmt
					.executeQuery("SELECT * FROM MyWebUsers WHERE username=user");
			rs.next();
			if (rs.getMetaData().getColumnCount() == 0)
				response.sendRedirect("./login.html");
			if (pswd.equals(rs.getString("password"))) {
				rd = ctx.getRequestDispatcher("/Welcome");
				rd.forward(request, response);
			} else
				response.sendRedirect("./login.html");

		} catch (Exception e) {
			response.getWriter().write(e.toString());
		}

	}
}
